import { ref, computed } from "vue";

export function usePager({
  request,
  pageSize = 10,
  isPush = true,
  runNow = false,
  replaceAfter = true,
} = {}) {
  const loading = ref(false);
  const error = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  const pageNum = ref(0);
  const list = ref([]);
  const totalNum = ref(0);
  const errorText = ref("请求失败");
  const loadingText = ref("数据加载中");
  const finishedText = computed(() => {
    return list.value.length === 0 ? "暂无数据" : "没有更多了";
  });
  const thePageSize = ref(pageSize);
  const totalPage = computed(() => {
    let num = 0;
    if (thePageSize.value > 0) {
      num = totalNum.value / thePageSize.value;
      if (totalNum.value % thePageSize.value !== 0) {
        num++;
      }
    }
    return num || 1;
  });
  const empty = computed(() => {
    return list.value.length === 0 && finished.value;
  });
  const emptyText = computed(() => {
    return error.value ? errorText.value : finishedText.value;
  });
  const initing = computed(() => {
    return list.value.length === 0 && pageNum.value === 1 && loading.value;
  });
  let version = 0;

  const onLoad = async (toPageNum) => {
    loading.value = true;
    if (toPageNum) {
      pageNum.value = toPageNum;
    } else {
      pageNum.value++;
    }
    try {
      let theVersion = version;
      let { rows, total } = await request(pageNum.value, thePageSize.value);
      if (theVersion !== version) {
        return false;
      }
      totalNum.value = total;
      if (!isPush || (pageNum.value === 1 && replaceAfter)) {
        list.value = rows;
      } else {
        list.value.push(...rows);
      }
      finished.value = totalNum.value <= list.value.length;
      error.value = false;
    } catch (e) {
      error.value = true;
      if (!isPush || (pageNum.value === 1 && replaceAfter)) {
        list.value = [];
      }
      console.error(e);
    }

    loading.value = false;
    refreshing.value = false;
  };

  const onRefresh = (pageSize, clear) => {
    version++;
    finished.value = false;
    pageNum.value = 0;

    if ((isPush && !replaceAfter) || clear) {
      list.value = [];
    }

    error.value = false;
    totalNum.value = 0;

    if (pageSize > 0) {
      thePageSize.value = pageSize;
    }

    onLoad();
  };

  if (runNow) {
    onLoad();
  }

  return {
    loading,
    error,
    finished,
    refreshing,
    pageNum,
    pageSize: thePageSize,
    totalNum,
    totalPage,
    list,
    finishedText,
    errorText,
    empty,
    emptyText,
    initing,
    onLoad,
    onRefresh,
    loadingText
  };
}
